package net.ck.hzq;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import net.ck.hzq.wxapi.ResultActivity;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.model.TakePhotoOptions;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import Bean.AuthBean;
import Bean.AuthParamBean;
import Utils.HelloWordModel;
import Utils.SharedPrefStore;
import Utils.SystemDatas;
import Utils.ToastUtil;
import base.BaseTakePhotoActivity;
import base.CustomHelper;
import event.LoginEvent;
import photopicker.Image;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import util.LogUtils;
import util.PermissionUtils;
import widget.CitySelectView;

import static Utils.FileUtil.compress;

public class RealNameActivity extends BaseTakePhotoActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_FACE = 203;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_BANKCARD = 111;
    private static final int REQUEST_CODE_BANKCARDBACK = 112;
    private static final int REQUEST_CODE_BUSINESS_LICENSE = 113;
    private static final int REQUEST_CODE_DOOR = 114;
    private static final int REQUEST_CODE_ENVIRONMENT = 115;
    private static final int GET_PERMISSION_REQUEST = 2002;
    private String base64_sfzzm = "", base64_sfzfm = "", base64_zp = "", base64_yhk = "";
    //申请权限
    private final String[] PERMISSIONS = new String[]{android.Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    private final int REQUEST_WRITE = 2;


    private CitySelectView citySelectView;
    private TextView addressSelectTv,posauthbyhandsubmitbutton;
    private RelativeLayout head_layout;
    private String mAddressCode;
    private ImageView idFrontIv,ivBackTv,ivHand,ivBank;

    private EditText detail_id_name,detail_id_no,et_bank_card_no,et_bank_card_name,et_open_account_bank;

    private Uri imageUri;
    private String mFilePath = "";// 需要初始化，路径自定义
    private boolean granted = false;

    private CustomHelper customHelper;

    private int clickType = -1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_real_name;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View contentView = LayoutInflater.from(this).inflate(R.layout.common_layout, null);
        customHelper = CustomHelper.of(contentView);
        head_layout = findViewById(R.id.head_layout);
        citySelectView = findViewById(R.id.city_rel_select_view);
        addressSelectTv = findViewById(R.id.address_rel_input);
        idFrontIv = findViewById(R.id.hand_image_id_rel_card_front);
        ivBackTv = findViewById(R.id.hand_image_id_card_back);
        ivHand = findViewById(R.id.hand_image_hold);
        ivBank = findViewById(R.id.hand_image_bank_card);
        detail_id_name = findViewById(R.id.detail_id_name);
        detail_id_no = findViewById(R.id.detail_id_no);
        et_bank_card_no = findViewById(R.id.et_bank_card_no);
        et_bank_card_name = findViewById(R.id.et_bank_card_name);
        et_open_account_bank = findViewById(R.id.et_open_account_bank);
        posauthbyhandsubmitbutton = findViewById(R.id.posauthbyhandsubmitbutton);
        File fileDir = new File(Environment.getExternalStorageDirectory(), "Pictures");
        if (!fileDir.exists()) {
            fileDir.getParentFile().mkdir();
        }
        mFilePath = fileDir.getAbsolutePath() + "/IMG_" + System.currentTimeMillis() + ".jpg";


        idFrontIv.setOnClickListener(this);
        ivBackTv.setOnClickListener(this);
        ivHand.setOnClickListener(this);
        ivBank.setOnClickListener(this);
        head_layout.setOnClickListener(view -> {
            finish();
        });
        posauthbyhandsubmitbutton.setOnClickListener(this);
        findViewById(R.id.address_rel_layout).setOnClickListener(this);
        citySelectView.setAddressSelectedListener((code, address) -> {
            mAddressCode = code;

            citySelectView.setVisibility(View.GONE);
            addressSelectTv.setText(address);
            addressSelectTv.setTextColor(getResources().getColor(R.color.tc_666666));
            LogUtils.d("+++++11111省市地址数据+++++++++++" + address);
        });
//        getPermissions();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.address_rel_layout: {
                citySelectView.setVisibility(View.VISIBLE);
                break;
            }
            case R.id.hand_image_id_rel_card_front: {
                clickType = 0;
                cameraClick(clickType,getTakePhoto());
                break;
            }
            case R.id.hand_image_id_card_back:{
                clickType = 1;
                cameraClick(clickType,getTakePhoto());
                break;
            }
            case R.id.hand_image_hold:{
                clickType = 2;
                cameraClick(clickType,getTakePhoto());
                break;
            }
            case R.id.hand_image_bank_card:{
                clickType = 3;
                cameraClick(clickType,getTakePhoto());
                break;
            }
            case R.id.posauthbyhandsubmitbutton:
                sendAuthRequest();
                break;
        }
    }

    //拍照
    private void cameraClick(int type,TakePhoto takePhoto) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true); //使用TakePhoto自带小相册
        builder.setCorrectImage(true); //纠正拍照的照片旋转角度
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private CropOptions getCropOptions() {
        int height = 600;
        int width = 800;
        boolean withWonCrop = false;

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = false;
        boolean enableRawFile = true;
        CompressConfig config;
//        if (rgCompressTool.getCheckedRadioButtonId() == R.id.rbCompressWithOwn) {
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
//        } else {
//            LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize).create();
//            config = CompressConfig.ofLuban(option);
//            config.enableReserveRaw(enableRawFile);
//        }
        takePhoto.onEnableCompress(config, showProgressBar);
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        showImg(result.getImages());

    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    private void showImg(ArrayList<TImage> images) {
        if (clickType == 0){

            base64_sfzzm = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(idFrontIv);
        }
        else if (clickType == 1){
            base64_sfzfm = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(ivBackTv);
        }
        else if (clickType == 2){
            base64_zp = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(ivHand);
        }
        else if (clickType == 3){
            base64_yhk = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(ivBank);
        }
    }


    /**
     * 发送实名认证请求
     */
    private void sendAuthRequest() {
        if(detail_id_no.getText().toString().equals("")||
                detail_id_name.getText().toString().equals("")||
                addressSelectTv.getText().toString().equals("")||
                et_bank_card_no.getText().toString().equals("")||
                et_open_account_bank.getText().toString().equals("")||
                et_bank_card_name.getText().toString().equals("")){
            Log.e("fjs","没拍摄照片");
            ToastUtil.show(RealNameActivity.this,"缺少必填参数！");


            return;
        }
        if(base64_sfzzm.equals("")||
                base64_sfzfm.equals("")||
                base64_zp.equals("")||
                base64_yhk.equals("")){
            Log.e("fjs","没拍摄照片");
            ToastUtil.show(RealNameActivity.this,"请拍摄所有照片！");


            return;
        }



        showProgressDialog();
        SharedPrefStore store = new SharedPrefStore();
        AuthParamBean param = new AuthParamBean();
        param.customId = store.getString("id", "0");
        param.idCardNumber = detail_id_no.getText().toString();
        param.name = detail_id_name.getText().toString();
        param.region = addressSelectTv.getText().toString();
        param.bankno = et_bank_card_no.getText().toString();
        param.bank = et_bank_card_name.getText().toString();
        param.bankadd = addressSelectTv.getText().toString();
        param.khzh = et_open_account_bank.getText().toString();
        param.idCardFrontImgData = base64_sfzzm;
        param.idCardBackImgData = base64_sfzfm;
        param.bankFrontImgData = base64_yhk;
        param.bankBackImgData = base64_yhk;
        param.headimgData = base64_zp;

        Call<AuthBean> userMsgCall = HelloWordModel.getInstance(RealNameActivity.this).auth(SystemDatas.GetService_URL("auth"), param);
        userMsgCall.enqueue(new Callback<AuthBean>() {
            @Override
            public void onResponse(@NonNull Call<AuthBean> call, @NonNull Response<AuthBean> response) {
                dismissProgressDialog();
                try {
                    if (response.body() != null && "401".equals(response.body().result)) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if (response.body() != null) {
                        if ("success".equals(response.body().msg)) {
                            ToastUtil.show(RealNameActivity.this, "提交成功");
                            finish();
                        } else {
                            showFailureTipDialog(response.body().msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<AuthBean> call, @NonNull Throwable t) {
                dismissProgressDialog();
                ToastUtil.show(RealNameActivity.this, "提交失败");
            }
        });
    }

    // 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
    @SuppressLint("NewApi")
    public static String getPathByUri4kitkat(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {// MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
            // (and
            // general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
            return uri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
//                //录音权限
//                int recordPermissionResult = grantResults[1];
//                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
//                if (!recordPermissionGranted) {
//                    size++;
//                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    granted = true;
//                    jCameraView.onResume();
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }

    }


}
